﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    public partial class form : Form
    {
        public form()
        {
            InitializeComponent();
        }
        private Socket socketSend;

        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //创建通信对象
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                //获取连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                ShowMessage("连接" + ip + ":" + btnSend.Text.Trim() + "成功！");

                //开启新线程不停接受服务端发送过来的消息
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //如果socket未连接，则退出
            if (socketSend == null || !socketSend.Connected)
            {
                MessageBox.Show("网络连接错误，请重新连入！");
                return;
            }

            try
            {
                var str = textBox4.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
                //发送成功后清空文本框
                textBox4.Text = string.Empty;
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }

        /// <summary>
        /// 不停接受服务器端的消息
        /// </summary>
        private void Receive()
        {
            while (true)
            {
                byte[] buffer = new Byte[1024 * 1024 * 5];
                int r = socketSend.Receive(buffer);

                if (r == 0)
                    break;

                //表示发送文字
                if (buffer[0] == 0)
                {
                    string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                    ShowMessage(socketSend.RemoteEndPoint + "：" + str);
                }
                //表示发送文件
                else if (buffer[0] == 1)
                {
                    //选择文件保存路径
                    var dialog = new SaveFileDialog();
                    dialog.InitialDirectory = @"c:\BBB";
                    dialog.Title = "请选择保存的文件夹";
                    dialog.Filter = "所有文件|*.*";
                    dialog.ShowDialog(this);

                    var path = dialog.FileName;

                    if (string.IsNullOrEmpty(path))
                    {
                        MessageBox.Show("请先选择保存文件夹！");
                        return;
                    }

                    try
                    {
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        if (Path.GetExtension(dialog.FileName) == ".png" || Path.GetExtension(dialog.FileName) == ".jpg")
                        {
                            pictureBox1.Image = Image.FromFile(dialog.FileName);
                        }

                        ShowMessage(socketSend.RemoteEndPoint + "：文件发送成功！");
                    }
                    catch
                    {
                        MessageBox.Show("网络访问错误，请重试！");
                        ShowMessage(socketSend.RemoteEndPoint + "：文件发送失败！");
                    }
                }
                //发送震动
                else if (buffer[0] == 2)
                {
                    Play();
                }
                else
                {
                    //其它的发送消息类型
                }
            }


        }

        private void form_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Play()
        {
            int leftWidth = this.Left; //指定窗体左边值
            int topWidth = this.Top; //指定窗体上边值 

            for (int i = 0; i < 20; i++) //设定循环次数为20 且加1
            {
                if (i % 2 == 0) //如果i 能给2整除 
                {
                    this.Left = this.Left + 5; //窗体左边值加10 
                }
                else //否则 
                {
                    this.Left = this.Left - 5;//窗体左边边值减10 
                }
                if (i % 2 == 0)//如果i能给2整除 
                {
                    this.Top = this.Top + 5;//窗体上边值加10 
                }
                else//否则 
                {
                    this.Top = this.Top - 5;//窗体上边值减10 
                }

                Thread.Sleep(15);//震动频率 
            }

            this.Left = leftWidth;//重设窗体初此左边值 
            this.Top = topWidth; //重设窗体初此上边值 
        }
    }
}
